package com.movies.service;

import com.movies.model.MovieUser;
import com.movies.model.MovieUserRole;
import com.movies.repository.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by admin on 2017/3/27.
 */
@Service
public class UserServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        MovieUser user = userMapper.findByUsername(username);
        if (null == user){
            throw new UsernameNotFoundException("用户名不存在");
        }
        return buildUserForAuthentication(user);
    }

    /**
     * 返回验证角色
     *
     * @param userRoles
     * @return
     */
    private List<GrantedAuthority> buildUserAuthority(Set<MovieUserRole> userRoles) {
        Set<GrantedAuthority> setAuths = new HashSet<GrantedAuthority>();
        for (MovieUserRole userRole : userRoles) {
            setAuths.add(new SimpleGrantedAuthority(userRole.getAuthority()));
        }
        List<GrantedAuthority> result = new ArrayList<GrantedAuthority>(setAuths);
        return result;
    }

    /**
     * 返回验证用户
     *
     * @param user
     * @return
     */
    private User buildUserForAuthentication(MovieUser user) {
        Set<MovieUserRole> userRoles = userMapper.getAuthorities(user.getUsername());
        List<GrantedAuthority> authorities = buildUserAuthority(userRoles);
        return new User(user.getUsername(), user.getPassword(), true, true, true, true, authorities);
    }

}
